<template>
  <div class="app-container">
    <div class="searchBox">
      <el-form ref="searchForm" :inline="true" :model="search">
        <el-form-item label="用户名称：">
          <el-input v-model="search.name" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="是否启用：" prop="isEnabled">
          <el-select v-model="search.isEnabled" clearable>
            <el-option
              v-for="item in enabledTypeOptions"
              :key="item.key"
              :label="item.value"
              :value="item.key"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="getTreeData">查询</el-button>
          <el-button type="info" @click="search = {};getTreeData()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <qm-table
      ref="qmTable"
      form-refs="qmGenForm"
      key-prop="workbenchId"
      :data="{ data: workbenchData }"
      :show-order="false"
      :show-pager="false"
      menu-type="text"
      :menu-options="{ width: 180 }"
      :form-options="{ labelWidth: '120px' }"
      :modal-options="{ height: 630 }"
      :form-validate="formValidate"
      :options="{
        rowId: 'workbenchId',
        border: false,
        treeConfig: { trigger: 'cell', reserve: true },
      }"
      :show-view="false"
      :show-checkbox="false"
      :is-custom-form="true"
      refresh-type="none"
      :refresh-func="treeRefresh"
      :remove-func="removeRow"
      :text-map="{ add: '新增' }"
    >
      <qm-table-column field="name" tree-node>名称</qm-table-column>
      <qm-table-column field="code">编码</qm-table-column>
      <qm-table-column field="openType" width="120px">打开类型</qm-table-column>
      <qm-table-column field="url">链接</qm-table-column>
      <qm-table-column field="isEnabled" width="120px" fieldtype="enabledisable">是否启用</qm-table-column>
      <qm-table-column field="memo">备注</qm-table-column>

      <template #moreBtn="{ row }">
        <el-button
          v-if="row.workbenchId"
          type="text"
          @click="addWorkbench(row)"
        >添加</el-button>
      </template>

      <template #form="{ models, controlData }">
        <operation
          ref="operationForm"
          :models="models"
          :control-data="controlData"
          :open-type-options="openTypeOptions"
          :enabled-type-options="enabledTypeOptions"
          :handle-tree="handleTree"
        />
      </template>
    </qm-table>
  </div>
</template>

<script>
import Controller from '@/libs/framework/controller'
import request from '@/utils/request'
import _ from 'lodash'
import IconSelect from '@/components/IconSelect'
import Operation from './operation'

export default class Instance extends Controller {
  onBeforeInit() {
    this.urls = {
      model: '/workflow/actExtWorkbench/getListModel',
      delete: '/workflow/actExtWorkbench/delete'
    }
  }

  onBeforeSave(postModel) {
    if (postModel.pageAction === 'create') {
      postModel.model.isDeleted = false
    }
    if (postModel.pageAction === 'edit' && !postModel.model.parentId) {
      postModel.model.parentId = ''
    }
    return true
  }

  onAfterGetEntity(result) {
    if (
      result &&
      result.models &&
      result.models.model &&
      result.pageAction === 'create'
    ) {
      result.models.model.parentId = this.vm.parentId || undefined
      this.vm.parentId = undefined
    }
  }

  mixin() {
    return {
      components: {
        IconSelect,
        Operation
      },
      data() {
        return {
          search: {},
          workbenchData: [],
          parentId: '',
          openTypeOptions: ['弹窗', '本窗口', '新窗口'],
          enabledTypeOptions: [
            { key: 1, value: '启用' },
            { key: 0, value: '禁用' }
          ]
        }
      },
      methods: {
        addWorkbench(row) {
          this.parentId = row.workbenchId
          this.$refs['qmTable'].addNew()
        },
        removeRow(rows) {
          const row = rows && rows.length ? rows[0] : {}
          const parent = this.$refs['qmTable'].getRowById(row.parentId)
          this.remove({ workbenchId: row.workbenchId }).then((r) => {
            if (r && r.success) {
              // 从数据源删除该行即可，不需要重新加载整棵树
              if (parent && parent.children) {
                parent.children.remove(row)
              } else {
                // 删除的是顶级的菜单
                this.workbenchData.remove(row)
              }
            }
          })
        },
        treeRefresh(params) {
          this.getTreeData()
        },
        getTreeData() {
          request({
            url: '/workflow/actExtWorkbench/workbenchList',
            method: 'post',
            params: this.search
          })
            .then((r) => {
              if (r && r.parameters && r.parameters.workbenchData) {
                this.workbenchData = this.handleTree(
                  r.parameters.workbenchData,
                  'workbenchId'
                )
              }
            })
            .catch((e) => {
              this.msgError('获取数据失败，请稍后再试')
            })
        },
        formValidate() {
          return this.$refs['operationForm'].$refs['qmGenForm'].validate()
        }
      },
      created() {
        this.getTreeData()
      }
    }
  }
}
</script>

<style scoped lang="scss">
</style>

